package com.project.controller;

import com.project.bean.CutPageBean;
import com.project.bean.LinkBean;
import com.project.service.ILinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("link")
public class LinkController {
    @Autowired
    private ILinkService service;

    @RequestMapping("cutAll")
    public String cutAll(@RequestParam(value = "pageNO",defaultValue = "1") int pageNO){
        //调用业务方法得到结果
        CutPageBean<LinkBean> cutBean = service.cutAll(pageNO);
        String str = "<table border='1' width='80%'>";
        str += "<thead><tr><th>姓名</th><th>生日</th><th>电话</th><th>操作</th></tr></thead>";

        str += "<tbody>";
        for(LinkBean link : cutBean.getList()){
            str += "<tr><td>"+link.getName()+"</td><td>"+link.getBirthday()+"</td>" +
                    "<td>"+link.getPhone()+"</td><td>" +
                    "<a href='/link/del?id="+link.getId()+"'>删除</a> <a href='/link/findById?id="+link.getId()+"'>修改</a></td></tr>";
        }
        str += "</tbody></table>";

        for(int i=1;i<=cutBean.getToalPage();i++){
            str += "<a href='/link/cutAll?pageNO="+i+"'>"+i+"</a> ";
        }

        str += "<div><a href='/addLink.html'>添加</a></div>";

        return str;
    }

    @RequestMapping("add")
    public String add(LinkBean link){
        service.add(link);
        return this.cutAll(1);
    }

    @RequestMapping("del")
    public String del(Integer id){
        service.del(id);
        return this.cutAll(1);
    }

    @RequestMapping("findById")
    public String  findById(Integer id){
        LinkBean link = service.findById(id);
        String str = "<form action='/link/update' method='post'>";
        str += "姓名："+link.getName()+"<br>";
        str += "生日："+link.getBirthday()+"<br>";
        str += "电话：<input type='text' name='phone' value='"+link.getPhone()+"'><br>";
        str += "<input type='hidden' name='id' value='"+link.getId()+"'>";
        str += "<input type='submit' value='修改'/>";

        str += "</form>";
        return str;
    }

    @RequestMapping("update")
    public String update(Integer id,String phone){
        service.update(id,phone);
        return this.cutAll(1);
    }

    @RequestMapping("show")
    public List<LinkBean> showLink(){
        List<LinkBean> list = new ArrayList<>();
        list.add(new LinkBean("张勇", LocalDate.parse("1992-03-04"),"1293283324"));
        list.add(new LinkBean("李仁", LocalDate.parse("1996-11-06"),"15930298323"));
        list.add(new LinkBean("刘三", LocalDate.parse("1998-08-24"),"13029382938"));
        return list;
    }
}
